﻿using Reader;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Linq;
using ConsumablesCabinet;
using IntelligentPharmacy.Entity;
using IntelligentPharmacy.publicclass;
using System.Collections.Concurrent;
using IntelligentPharmacy.httprequest;
using SmartRoom;

namespace SmartForcer
{
    /// <summary>
    /// MenuWindows.xaml 的交互逻辑
    /// </summary>
    public partial class MenuWindows : Window
    {
        requestService reques = new requestService();
        private ConfigManager configManager = new ConfigManager();
        #region 码货的读写器的
        private volatile Dictionary<string, ReaderMethod> listReader = new Dictionary<string, ReaderMethod>();
        
        private volatile Dictionary<string, ReaderSetting> m_curSettingList = new Dictionary<string, ReaderSetting>();
        //天线的配置文件

        private volatile Dictionary<string, InventoryBuffer> m_curInventoryBufferList = new Dictionary<string, InventoryBuffer>();
        //天线次数
        private volatile Dictionary<string, int> m_nReceiveFlagList = new Dictionary<string, int>();
        //盘存操作前，需要先设置工作天线，用于标识当前是否在执行盘存操作
        private volatile ConcurrentDictionary<string, bool> m_bInventoryList = new ConcurrentDictionary<string, bool>();
        //EPC标签
        private volatile Dictionary<string, string> EPCTag = new Dictionary<string, string>();
        #endregion
        /// <summary>
        /// 存打开门的集合 门开为true
        /// </summary>
       // private volatile  Dictionary<string, bool> ifDoors = new Dictionary<string, bool>();
        private volatile ConcurrentDictionary<string, bool> ifDoors = new ConcurrentDictionary<string, bool>();
        /// <summary>
        /// 检测门的线程
        /// </summary>
        private System.Windows.Forms.Timer _startTimer = new System.Windows.Forms.Timer();
        /// <summary>
        ///  //启动盘点的线程
        /// </summary>
        private System.Windows.Forms.Timer _inventoryTimer = new System.Windows.Forms.Timer();
        /// <summary>
        /// 
        /// </summary>
        private ConcurrentDictionary<string, int> openDoorDate = new ConcurrentDictionary<string, int>();
        bool isCheck = false;
        

        public MenuWindows()
        {
            InitializeComponent();
            try
            {
                Global.AfterRfidList.Clear();
                loadReader();//连接读写器
            }catch(Exception ex) { }
        }
 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Global.User != null)
                    lbl_LogName.Content = Global.User.empName;
                lbl_ks.Content = ReadAppConfig.readerWarehouseName();
                LoadMenu();
                //检测是否关门的线程
                _startTimer.Interval = 1000;
                _startTimer.Tick += new EventHandler(StartInventory);
                //启动盘点的线程
                _inventoryTimer.Interval = 300;
                _inventoryTimer.Tick += new EventHandler(timerInventory_Tick);
            }catch(Exception ex) { }
        }
        public void loadReader()
        {
            #region 连接读写器
            foreach (KeyValuePair<string, int> item in Global.comeAndPower)
            {
                ReaderSetting m_curSetting = new ReaderSetting();
                InventoryBuffer m_curInventoryBuffer = new InventoryBuffer();
                ReaderMethod reader = new Reader.ReaderMethod();

                string strException = string.Empty;
                try
                {
                    int nRet = reader.OpenCom(item.Key, 115200, out strException);
                    if (nRet != 0)
                    {
                        reader = null;
                        string strLog = "连接读写器失败，失败原因： " + strException;
                        Global.MessageWindow.ShowDialog(strLog, Enum.MessageButton.Close, Enum.MessageStyle.Error);
                        return;
                    }
                }
                catch (Exception ea)
                {
                    System.Windows.MessageBox.Show(ea.Message);
                }

                ifDoors.GetOrAdd(item.Key, false);
                listReader.Add(item.Key, reader);
                reader.SetOutputPower(m_curSetting.btReadId, Convert.ToByte(item.Value));
                m_curSetting.btOutputPower = Convert.ToByte(item.Value);

                m_nReceiveFlagList.Add(item.Key, 0);
                m_curSettingList.Add(item.Key, m_curSetting);
                m_curInventoryBufferList.Add(item.Key, m_curInventoryBuffer);
                m_bInventoryList.GetOrAdd(item.Key, false);
                //回调函数
                reader.AnalyCallback = AnalyData;

                doorCount.GetOrAdd(item.Key, 0);

            }
            #endregion
        }
        /// <summary>
        /// 校验读写器并且重新连接
        /// </summary>
        public void chackReaderWriter()
        {
            #region 检测天线是否正常
            // #region 检测天线是否正常
            foreach (KeyValuePair<string, ReaderMethod> item in listReader)
            {
                ReaderMethod itemRead = item.Value;
                if (!itemRead.getSerialPort().IsOpen)
                {
                    string[] gCOM = System.IO.Ports.SerialPort.GetPortNames();
                    foreach (string items in gCOM)
                    {
                        string portName = itemRead.getSerialPort().PortName;
                        if (items.Equals(portName))
                        {
                            itemRead.getSerialPort().Open();
                        }
                    }
                }
            }
            #endregion
        }

        /// <summary>
        /// 检测关门的次数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ConcurrentDictionary<string, int> doorCount = new ConcurrentDictionary<string, int>();
        public void StartInventory(object sender,EventArgs e)
        {
            try
            {
                chackReaderWriter();

                int ifretur = 0;

                foreach (KeyValuePair<string, bool> item in ifDoors)
                {
                    if (item.Value)
                    {
                        openDoorDate[item.Key] += _startTimer.Interval;
                        //if(openDoorDate[item.Key] > Global.LockTime && doorCount[item.Key] == 0)
                        if (openDoorDate[item.Key] > Global.LockTime && doorCount[item.Key] == 0)
                        {
                            doorCount[item.Key]++;
                            WriteGpio(listReader[item.Key], 0x00, item.Key);//关门
                        }
                        else if (doorCount[item.Key] > 0)
                        {
                            listReader[item.Key].ReadGpioValue(m_curSettingList[item.Key].btReadId);
                        }
                        ++ifretur;
                        continue;
                    }
                }
                if (ifretur != 0) return;
                foreach (KeyValuePair<string, bool> item in ifDoors)
                {

                    openDoorDate[item.Key] = 0;
                }
                foreach (KeyValuePair<string, bool> dooritem in ifDoors)
                {
                    doorCount[dooritem.Key] = 0;
                }
                return;
                Thread.Sleep(1000);
                _startTimer.Enabled = false;
                _inventoryTimer.Enabled = true;
                EPCTag.Clear();
                Global.MessageWindow.ShowDialog1("正在盘点中，请稍等" + Global.readTime / 1000 + "秒");
            }catch(Exception ex) { }
        }
        /// <summary>
        /// 盘点读取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private int isCheckTime = 0;
        private bool readOpneOrClose = true;
        private void timerInventory_Tick(object sender, EventArgs e)
        {
            try
            {
                chackReaderWriter();
                foreach (KeyValuePair<string, ReaderMethod> item in listReader)
                {
                    if (readOpneOrClose)
                    {
                        //设置天线参数
                        setUHFConfig(item.Key);
                    }
                    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
                    {
                        m_nReceiveFlagList[item.Key]++;
                        if (m_nReceiveFlagList[item.Key] >= 5)
                        {
                            RunLoopInventroy(item.Key);
                            m_nReceiveFlagList[item.Key] = 0;
                        }
                    }));
                }
                readOpneOrClose = false;
                isCheckTime += _inventoryTimer.Interval;
                if (isCheckTime >= Global.readTime)
                {
                    foreach (KeyValuePair<string, ReaderMethod> item in listReader)
                    {
                        if(item.Key != null)
                        {
                            m_bInventoryList[item.Key] = false;
                            m_curInventoryBufferList[item.Key].bLoopInventory = false;
                        }
                    }
                    _inventoryTimer.Enabled = false;
                    //进来的时候加载所有标签
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    List<TagEntity> listTag = reques.getStockList();
                    foreach (TagEntity tag in listTag)
                    {
                        if(tag.rfid != null)
                        {
                            dic.Add(tag.rfid, "");
                        }
                    }
                    Global.AfterRfidList = dic;

                    #region 出入库
                    List<TagEntity> putlists = new List<TagEntity>();//入库
                    List<TagEntity> outlists = new List<TagEntity>();//出库
                    if (Global.AfterRfidList.Count <= 0)//入库
                    {
                        Global.AfterRfidList = EPCTag;
                        foreach (KeyValuePair<string, string> item in Global.AfterRfidList)
                        {
                            if(item.Key != null)
                            {
                                TagEntity ta = new TagEntity();
                                ta.rfid = item.Key;
                                putlists.Add(ta);
                            }
                        }
                    }
                    else
                    {
                        foreach (KeyValuePair<string, string> item in EPCTag)
                        {
                            if (!Global.AfterRfidList.ContainsKey(item.Key))//入库
                            {
                                if(item.Key != null)
                                {
                                    TagEntity ta = new TagEntity();
                                    ta.rfid = item.Key;
                                    putlists.Add(ta);
                                }
                            }
                        }
                        foreach (KeyValuePair<string, string> outitem in Global.AfterRfidList)//出库
                        {
                            if (!EPCTag.ContainsKey(outitem.Key))
                            {
                                TagEntity ta = new TagEntity();
                                ta.rfid = outitem.Key;
                                outlists.Add(ta);
                            }
                        }
                    }
                    try
                    {
                        Global.MessageWindow.Hide();
                    }
                    catch { }
                    isCheckTime = 0;
                    readOpneOrClose = true;
                    //跳转到页面
                    InDetailWindow inDetailWindow = new InDetailWindow(outlists, putlists, EPCTag);
                    Global.WindowsList.Add(inDetailWindow);
                    inDetailWindow.ShowDialog();
                    Global.WindowsList.Remove(inDetailWindow);

                    //重新盘点
                    if (inDetailWindow.dialogResult == Enum.MessageDialogResult.Cancel)
                    {
                        Global.AfterRfidList.Clear();
                        EPCTag.Clear();
                        dic.Clear();
                        putlists.Clear();
                        outlists.Clear();
                        _inventoryTimer.Enabled = true;
                        Global.MessageWindow.ShowDialog1("正在盘点中，请稍等" + Global.readTime / 1000 + "秒");
                    }


                    #endregion
                }
            }catch(Exception ex)
            {
                Global.MessageWindow.Hide();
                string strLog = "盘点时出错,出错原因： " + ex.Message;
                Global.MessageWindow.ShowDialog(strLog, Enum.MessageButton.Close, Enum.MessageStyle.Error);
            }
        }
        #region 动态加载菜单
        void LoadMenu()
        {
            int i = 0;
            int ImageWidth = 1900 / Global.comeAndPower.Count;
            foreach (KeyValuePair<string,int> com in Global.comeAndPower)
            {
                MyGrid.ColumnDefinitions.Add(new ColumnDefinition());
                Uri uri = null;
                if (com.Key == Global.MainForcer)
                {
                    uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "Asset\\images\\NewMenu\\A-1.jpg", UriKind.Absolute);
                }
                else
                {
                    uri = new Uri(AppDomain.CurrentDomain.BaseDirectory+"Asset\\images\\NewMenu\\B-1.jpg", UriKind.Absolute);
                }
                Image image = new Image();
                image.Name = com.Key; // 标记
                image.Opacity = 0.8;
                image.Stretch = Stretch.Fill;
                //image.Width = ImageWidth;                
                //image.Height = 600;
                image.Source = new BitmapImage(uri);
                image.Tag = com.Key;

                image.MouseLeftButtonDown += Image_MouseLeftButtonDown;

                RectangleGeometry rg = new RectangleGeometry();
                rg.Rect = new Rect(0, 0, ImageWidth, 860);
                rg.RadiusX = 10;
                rg.RadiusY = 10;
                image.Clip = rg;
                MyGrid.Children.Add(image); //添加到Grid控件
                image.SetValue(Grid.RowProperty, 0); //设置按钮所在Grid控件的行
                image.SetValue(Grid.ColumnProperty, i); //设置按钮所在Grid控件的列     
                i++;
            }
        }    
        #endregion

        /// <summary>
        /// 打开柜门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                chackReaderWriter();
                isCheck = false;
                string comeName = Convert.ToString((sender as Image).Name);
                WriteGpio(listReader[comeName], 0x01,comeName);// 打开柜门
                doorCount[comeName]=0;
                foreach (KeyValuePair<string,ReaderMethod> item in listReader)
                {
                    if (item.Key.Equals(comeName))
                    {
                        ifDoors[comeName] = true;
                        if (!openDoorDate.ContainsKey(comeName))
                        {
                            openDoorDate.GetOrAdd(comeName, 0);
                        }
                        else
                        {
                            openDoorDate[comeName] = 0;
                        }
                    }
                }
                if (!_startTimer.Enabled)
                    _startTimer.Enabled= true;
            }
            catch (Exception ex)
            {
                Global.MessageWindow.ShowDialog("打开柜门出现异常!"+ex.Message, Enum.MessageButton.Cancel, Enum.MessageStyle.Warn);
            }
        }
        private void WriteGpio(ReaderMethod reader, byte btGpioValue, string com)
        {
           
            reader.WriteGpioValue(m_curSettingList[com].btReadId, 0x04, btGpioValue);
            m_curSettingList[com].btGpio4Value = btGpioValue;
        }


        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                foreach (var reader in listReader)
                {
                    reader.Value.CloseCom();
                }
                if (_inventoryTimer != null)
                {
                    _inventoryTimer.Dispose();
                    _inventoryTimer = null;
                }
                if (_startTimer != null)
                {
                    _startTimer.Dispose();
                    _startTimer = null;
                }
            }
            catch (Exception ex)
            { }
        }

        private void bdrTop_MouseDown(object sender, MouseButtonEventArgs e)
        {
            foSearch.IsOpen = !foSearch.IsOpen;
        }
        /// <summary>
        /// 手动开始盘点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void img_CheckStorage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isCheck = true;
            if (!_startTimer.Enabled)
                _startTimer.Enabled=true;
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Back_TouchDown(object sender, TouchEventArgs e)
        {
            try
            {
              
                foreach (KeyValuePair<string, bool> item in ifDoors)
                {
                    if (item.Value)
                    {
                        Global.MessageWindow.ShowDialog("请关闭门");
                        return;
                    }
                }
                this.Close();
            }catch(Exception ex) { }
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Back_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                
                foreach (KeyValuePair<string, bool> item in ifDoors)
                {
                    if (item.Value)
                    {
                        Global.MessageWindow.ShowDialog("请关闭门");
                        return;
                    }
                }
                this.Close();
            }catch(Exception ex) { }
        }
        #region 通道机上面读写器部分
        private bool isThreadNumber()
        {
            int workerThreads = 0;
            int maxWordThreads = 0;
            int complaThread = 0;
            ThreadPool.GetAvailableThreads(out workerThreads, out complaThread);
            ThreadPool.GetMaxThreads(out maxWordThreads, out complaThread);
            if (workerThreads == maxWordThreads)
            {
                return true;
            }
            return false;
        }

        private void RunLoopInventroy(string adrress)
        {
            //校验盘存是否所有天线均完成
            if (m_curInventoryBufferList[adrress].nIndexAntenna < m_curInventoryBufferList[adrress].lAntenna.Count - 1 || m_curInventoryBufferList[adrress].nCommond == 0)
            {
                if (m_curInventoryBufferList[adrress].nCommond == 0)
                {
                    m_curInventoryBufferList[adrress].nCommond = 1;

                    if (m_curInventoryBufferList[adrress].bLoopInventoryReal)
                    {
                        if (m_curInventoryBufferList[adrress].bLoopCustomizedSession)//自定义Session和Inventoried Flag 
                        {
                            listReader[adrress].CustomizedInventory(m_curSettingList[adrress].btReadId, m_curInventoryBufferList[adrress].btSession, m_curInventoryBufferList[adrress].btTarget, m_curInventoryBufferList[adrress].btRepeat);
                        }
                        else //实时盘存
                        {
                            listReader[adrress].InventoryReal(m_curSettingList[adrress].btReadId, m_curInventoryBufferList[adrress].btRepeat);
                        }
                    }
                    else
                    {
                        if (m_curInventoryBufferList[adrress].bLoopInventory)
                            listReader[adrress].Inventory(m_curSettingList[adrress].btReadId, m_curInventoryBufferList[adrress].btRepeat);
                    }
                }
                else
                {
                    m_curInventoryBufferList[adrress].nCommond = 0;
                    m_curInventoryBufferList[adrress].nIndexAntenna++;

                    byte btWorkAntenna = m_curInventoryBufferList[adrress].lAntenna[m_curInventoryBufferList[adrress].nIndexAntenna];
                    listReader[adrress].SetWorkAntenna(m_curSettingList[adrress].btReadId, btWorkAntenna);
                    m_curSettingList[adrress].btWorkAntenna = btWorkAntenna;
                }
            }
            //校验是否循环盘存
            else if (m_curInventoryBufferList[adrress].bLoopInventory)
            {
                m_curInventoryBufferList[adrress].nIndexAntenna = 0;
                m_curInventoryBufferList[adrress].nCommond = 0;

                byte btWorkAntenna = m_curInventoryBufferList[adrress].lAntenna[m_curInventoryBufferList[adrress].nIndexAntenna];
                listReader[adrress].SetWorkAntenna(m_curSettingList[adrress].btReadId, btWorkAntenna);
                m_curSettingList[adrress].btWorkAntenna = btWorkAntenna;
            }
        }

        private void setUHFConfig(string address)
        {

            try
            {
                m_curInventoryBufferList[address].ClearInventoryPar();
                //每一条命令盘存的次数
                m_curInventoryBufferList[address].btRepeat = Global.btRepeat;

                if (Global.RealSession)//是否开启自定义session
                {
                    m_curInventoryBufferList[address].bLoopCustomizedSession = true;
                    m_curInventoryBufferList[address].btSession = (byte)Global.Session;//设置的session
                    m_curInventoryBufferList[address].btTarget = Global.btTarget;//页面上面的Inventoried Flag:
                }
                else
                {
                    m_curInventoryBufferList[address].bLoopCustomizedSession = false;
                }
                string[] tx = Global.tdjTDJAerial.Split(',');
                foreach (string txm in tx)
                    m_curInventoryBufferList[address].lAntenna.Add((byte)Convert.ToInt32(txm));//设置天线你 
                m_curInventoryBufferList[address].bLoopInventory = true;//?


                m_bInventoryList[address] = true;

                m_curInventoryBufferList[address].bLoopInventoryReal = true;//开启盘存
                m_curInventoryBufferList[address].ClearInventoryRealResult();


                //不明白
                byte btWorkAntenna = m_curInventoryBufferList[address].lAntenna[m_curInventoryBufferList[address].nIndexAntenna];
                m_curSettingList[address].btWorkAntenna = btWorkAntenna;
                listReader[address].SetWorkAntenna(m_curSettingList[address].btReadId, btWorkAntenna);
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show("天线设置错误" + e.Message);
            }
        }

        /// <summary>
        /// 回调函数对数据进行处理
        /// </summary>
        /// <param name="msgTran"></param>
        private void AnalyData(Reader.MessageTran msgTran)
        {
            if (msgTran.PacketType != 0xA0)
            {
                return;
            }
            switch (msgTran.Cmd)
            {
                case 0x74:
                    ProcessSetWorkAntenna(msgTran);//设置读写器工作天线
                    break;
                case 0x89:
                case 0x8B:
                    ProcessInventoryReal(msgTran);//自定义session和target盘存
                    break;
                case 0x79:
                    ProcessGetFrequencyRegion(msgTran);//查询读写器工作频率范围
                    break;
                case 0x60:
                    ProcessReadGpioValue(msgTran);//读取GPIO电平
                    break;
                default:
                    break;
            }
        }

        private void ProcessReadGpioValue(Reader.MessageTran msgTran)
        {
            string strCmd = "读取GPIO状态";
            string strErrorCode = string.Empty;

            if (msgTran.AryData.Length == 2)
            {
                m_curSettingList[msgTran.DeviceName].btReadId = msgTran.ReadId;
                m_curSettingList[msgTran.DeviceName].btGpio1Value = msgTran.AryData[0];
                m_curSettingList[msgTran.DeviceName].btGpio2Value = msgTran.AryData[1];
                RefreshReadSetting(msgTran);
                return;
            }
            else if (msgTran.AryData.Length == 1)
            {
                strErrorCode = CCommondMethod.FormatErrorCode(msgTran.AryData[0]);
            }
            else
            {
                strErrorCode = "未知错误";
            }

            string strLog = strCmd + "失败，失败原因： " + strErrorCode;
        }


        private delegate void RefreshReadSettingUnsafe(Reader.MessageTran msgTran);
        private void RefreshReadSetting(Reader.MessageTran msgTran)
        {

            if (this.CheckAccess())
            {
                RefreshReadSettingUnsafe InvokeRefresh = new RefreshReadSettingUnsafe(RefreshReadSetting);
                this.Dispatcher.Invoke(InvokeRefresh, new object[] { msgTran });
            }
            else
            {
                switch (msgTran.Cmd)
                {
                    case 0x60:
                        {
                            if ( m_curSettingList[msgTran.DeviceName].btGpio1Value == 0x00)
                            {
                               //rdbGpio1Low.Checked = true;
                            }
                            if (m_curSettingList[msgTran.DeviceName].btGpio2Value == 0x01)
                            {
                                //当前使用gpio2\
                                // MessageBox.Show("门已经关闭");
                                ifDoors[msgTran.DeviceName] = false;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void ProcessGetFrequencyRegion(MessageTran msgTran)
        {
            string strCmd = "取得射频规范";
            string strErrorCode = string.Empty;

            if (msgTran.AryData.Length == 3)
            {
                m_curSettingList[msgTran.DeviceName].btReadId = msgTran.ReadId;
                m_curSettingList[msgTran.DeviceName].btRegion = msgTran.AryData[0];
                m_curSettingList[msgTran.DeviceName].btFrequencyStart = msgTran.AryData[1];
                m_curSettingList[msgTran.DeviceName].btFrequencyEnd = msgTran.AryData[2];
                return;
            }
            else if (msgTran.AryData.Length == 6)
            {
                m_curSettingList[msgTran.DeviceName].btReadId = msgTran.ReadId;
                m_curSettingList[msgTran.DeviceName].btRegion = msgTran.AryData[0];
                m_curSettingList[msgTran.DeviceName].btUserDefineFrequencyInterval = msgTran.AryData[1];
                m_curSettingList[msgTran.DeviceName].btUserDefineChannelQuantity = msgTran.AryData[2];
                m_curSettingList[msgTran.DeviceName].nUserDefineStartFrequency = msgTran.AryData[3] * 256 * 256 + msgTran.AryData[4] * 256 + msgTran.AryData[5];
                return;


            }
            else if (msgTran.AryData.Length == 1)
            {
                strErrorCode = CCommondMethod.FormatErrorCode(msgTran.AryData[0]);
            }
            else
            {
                strErrorCode = "未知错误";
            }
            string strLog = strCmd + "失败，失败原因： " + strErrorCode;
        }
        private void ProcessInventoryReal(MessageTran msgTran)
        {
            string strErrorCode = string.Empty;

            if (msgTran.AryData.Length == 1)
            {
                strErrorCode = CCommondMethod.FormatErrorCode(msgTran.AryData[0]);

                RefreshInventoryReal(0x00);
                RunLoopInventroy(msgTran.DeviceName);
            }
            else if (msgTran.AryData.Length == 7)
            {
                m_curInventoryBufferList[msgTran.DeviceName].nReadRate = Convert.ToInt32(msgTran.AryData[1]) * 256 + Convert.ToInt32(msgTran.AryData[2]);
                m_curInventoryBufferList[msgTran.DeviceName].nDataCount = Convert.ToInt32(msgTran.AryData[3]) * 256 * 256 * 256 + Convert.ToInt32(msgTran.AryData[4]) * 256 * 256 + Convert.ToInt32(msgTran.AryData[5]) * 256 + Convert.ToInt32(msgTran.AryData[6]);

                RefreshInventoryReal(0x01);
                RunLoopInventroy(msgTran.DeviceName);
            }
            else
            {
                int nLength = msgTran.AryData.Length;
                int nEpcLength = nLength - 4;
                string strEPC = CCommondMethod.ByteArrayToString(msgTran.AryData, 3, nEpcLength).Trim();

                strEPC = strEPC.Trim().Replace(" ", "");
                if (!EPCTag.ContainsKey(strEPC))
                {
                    EPCTag.Add(strEPC, msgTran.DeviceName.ToUpper());
                }
                m_curInventoryBufferList[msgTran.DeviceName].dtEndInventory = DateTime.Now;
                RefreshInventoryReal(0x89);
            }
        }

        private delegate void RefreshInventoryRealUnsafe(byte btCmd);
        private void RefreshInventoryReal(byte btCmd)
        {
            if (this.CheckAccess())
            {
                RefreshInventoryRealUnsafe InvokeRefresh = new RefreshInventoryRealUnsafe(RefreshInventoryReal);
                this.Dispatcher.Invoke(InvokeRefresh, new object[] { btCmd });
            }
            else
            {
                switch (btCmd)
                {
                    case 0x89:
                    case 0x8B:
                        {
                        }
                        break;
                    case 0x00:
                    case 0x01:
                        break;
                    default:
                        break;
                }
            }
        }

        private void ProcessSetWorkAntenna(MessageTran msgTran)
        {
            int intCurrentAnt = 0;
            intCurrentAnt = m_curSettingList[msgTran.DeviceName].btWorkAntenna + 1;
            string strCmd = "设置工作天线成功,当前工作天线: 天线" + intCurrentAnt.ToString();

            string strErrorCode = string.Empty;

            if (msgTran.AryData.Length == 1)
            {
                if (msgTran.AryData[0] == 0x10)
                {
                    m_curSettingList[msgTran.DeviceName].btReadId = msgTran.ReadId;
                    //校验是否盘存操作
                    if (m_bInventoryList[msgTran.DeviceName])
                    {
                        RunLoopInventroy(msgTran.DeviceName);
                    }
                    return;
                }
                else
                {
                    strErrorCode = CCommondMethod.FormatErrorCode(msgTran.AryData[0]);
                }
            }
            else
            {
                strErrorCode = "未知错误";
            }
            if (m_bInventoryList[msgTran.DeviceName])
            {
                m_curInventoryBufferList[msgTran.DeviceName].nCommond = 1;
                m_curInventoryBufferList[msgTran.DeviceName].dtEndInventory = DateTime.Now;
                RunLoopInventroy(msgTran.DeviceName);
            }
        }

        #endregion
        /// <summary>
        /// 手动盘点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonDown_8(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (listReader.Count == 0)
                {
                    Global.MessageWindow.ShowDialog("没有连接到读写器");
                    return;
                }
                _inventoryTimer.Enabled = true;
                EPCTag.Clear();
                Global.MessageWindow.ShowDialog1("正在盘点中，请稍等" + Global.readTime / 1000 + "秒");
            }catch(Exception ex) {

            }
        }
        /// <summary>
        /// 库存查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonDown_9(object sender, MouseButtonEventArgs e)
        {
            try
            {
                _startTimer.Enabled = false;
                _inventoryTimer.Enabled = false;
                Global.MessageWindow.Hide();
                OutDetailWindow outwindows = new OutDetailWindow();
                Global.WindowsList.Add(outwindows);
                outwindows.ShowDialog();
                Global.WindowsList.Remove(outwindows);
                _startTimer.Enabled = true;
            }
            catch(Exception ex) { }
        }
        /// <summary>
        /// 出入库记录查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeftButtonDown_10(object sender, MouseButtonEventArgs e)
        {
            try
            {
                _startTimer.Enabled = false;
                _inventoryTimer.Enabled = false;
                Global.MessageWindow.Hide();
                LYJLCXWindows LYGH = new LYJLCXWindows();
                Global.WindowsList.Add(LYGH);
                LYGH.ShowDialog();
                Global.WindowsList.Remove(LYGH);
                _startTimer.Enabled = true;
            }
            catch(Exception ex) { }
        }
    }
}
